﻿using MES.Desktop.Common;
using MES.Desktop.IService;
using MES.Desktop.SystemModule.Models;
using Prism.Events;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MES.Desktop.SystemModule.ViewModels
{
    public class PostViewModel : PageViewModelBase
    {
        public ObservableCollection<PostModel> Posts { get; set; } =
            new ObservableCollection<PostModel>();

        private bool isSyncSelect;
        private bool _isSelectAll;

        public bool IsSelectAll
        {
            get { return _isSelectAll; }
            set
            {
                SetProperty<bool>(ref _isSelectAll, value);

                if (isSyncSelect) return;
                isSyncSelect = true;

                foreach (var post in Posts)
                    post.IsSelected = value;

                isSyncSelect = false;
            }
        }


        IPostService _postService;
        IEventAggregator _eventAggregator;
        IDialogService _dialogService;
        public PostViewModel(
            IRegionManager regionManager,
            IPostService postService,
            IEventAggregator eventAggregator,
            IDialogService dialogService)
            : base(regionManager)
        {
            this.PageTitle = "职位信息管理";

            _postService = postService;
            _eventAggregator = eventAggregator;
            _dialogService = dialogService;

            this.Refresh();
        }

        public override void Refresh()
        {
            Posts.Clear();

            _eventAggregator.GetEvent<LoadingEvent>()
                .Publish("正在加载职位....");

            Task.Run(() =>
            {
                try
                {
                    var posts = _postService.GetAllPosts(SearchKey).ToList();
                    for (int i = 0; i < posts.Count; i++)
                    {
                        var depart = posts[i];

                        PostModel model = new PostModel();
                        model.Index = i + 1;
                        model.PostId = posts[i].PostId;
                        model.PostName = posts[i].PostName;

                        model.PropertyChanged += (se, ev) =>
                        {
                            if (isSyncSelect) return;
                            isSyncSelect = true;

                            if (ev.PropertyName == "IsSelected")
                                this.IsSelectAll = Posts.All(f => f.IsSelected);

                            isSyncSelect = false;
                        };

                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            Posts.Add(model);
                        });
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "提示");
                }
                finally
                {
                    _eventAggregator.GetEvent<LoadingEvent>()
                        .Publish("");
                }
            });
        }

        public override void DoBatchDelete()
        {
            var ids = Posts.Where(d => d.IsSelected)
                  .Select(d => d.PostId.ToString())
                  .ToArray();

            this.DeleteDepart(ids);
        }

        public override void DoDelete(object obj)
        {
            string[] ids = new string[] { (obj as PostModel).PostId.ToString() };
            this.DeleteDepart(ids);
        }

        private void DeleteDepart(string[] ids)
        {
            var mb_result = MessageBox.Show("请确认删除当前记录!", "提示", MessageBoxButton.YesNo);
            if (mb_result != MessageBoxResult.Yes) return;

            _eventAggregator.GetEvent<LoadingEvent>()
                .Publish("正在删除职位....");

            Task.Run(() =>
            {
                try
                {
                    int count = _postService.DeletePosts(ids);
                    if (count == 0)
                    {
                        throw new Exception("删除职位失败");
                    }

                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        this.Refresh();
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "提示");
                }
                finally
                {
                    _eventAggregator.GetEvent<LoadingEvent>()
                        .Publish("");
                }
            });
        }

        public override void DoModify(object obj)
        {
            DialogParameters ps = new DialogParameters();
            ps.Add("model", obj);

            _dialogService.ShowDialog("ModifyPostView", ps, result =>
            {
                // 判断子窗口的返回状态，如果OK，刷新当前页面，否则不管
                if (result.Result == ButtonResult.OK)
                {
                    this.Refresh();
                }
            });
        }
    }
}
